package utils

import (
	"encoding/binary"
	"encoding/json"
	"fmt"
	"go_code/chatroom/client/message"
	"net"
)

type Transport struct {
	Conn net.Conn
	Buf  [1024]byte
}

func (t *Transport) WritePkg(msg *message.Message) error {
	var pkgLen uint32
	data, _ := json.Marshal(msg)

	pkgLen = uint32(len(data))
	binary.BigEndian.PutUint32(t.Buf[0:4], pkgLen)

	_, err := t.Conn.Write(t.Buf[0:4])
	if err != nil {
		fmt.Println("Client WritePkg 发送数据长度失败", err)
		return err
	}

	_, err = t.Conn.Write(data)
	if err != nil {
		fmt.Println("Client WritePkg 发送数据消息失败", err)
		return err
	}

	return nil
}

func (t *Transport) ReadPkg() (msg *message.Message, err error) {
	var pkgLen uint32

	_, err = t.Conn.Read(t.Buf[0:4])
	if err != nil {
		fmt.Println("Client ReadPkg 读取数据长度失败", err)
		return
	}

	pkgLen = binary.BigEndian.Uint32(t.Buf[0:4])

	n, err := t.Conn.Read(t.Buf[:pkgLen])
	if err != nil || uint32(n) != pkgLen {
		fmt.Println("Client ReadPkg 读取数据消息失败", err)
		return
	}

	err = json.Unmarshal(t.Buf[:pkgLen], &msg)
	if err != nil {
		fmt.Println("Client ReadPkg 反序列化数据消息失败", err)
		return
	}

	return
}
